<template>
  <div class="edit-stock-dialog">
    <el-dialog
      :title="$t('stock.修改库存')"
      :visible.sync="computedDialogVisible"
      width="520px"
    >
      <el-form ref="form">
        <el-form-item
            :label="$t('stock.当前库存')"
        >
          {{ currentStock }}
        </el-form-item>
        <el-form-item
            :label="$t('stock.修改后的库存')"
        >
          <el-input-number v-model="formStock"></el-input-number>
          <div class="tips">{{ $t('stock.请与用户核对好商品最终数量后再保存当前信息') }}</div>
        </el-form-item>
        <el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="submitPacketStock()" :loading="loading">{{$t('common.save')}}</el-button>
            <el-button size="small" @click="computedDialogVisible = false">{{$t('common.cancel')}}</el-button>
          </el-form-item>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {editStockNum} from "@/api/stock";

export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    currentSuit: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      loading: false,
      currentStock: 0,
      formStock: 0,
    }
  },
  computed: {
    computedDialogVisible: {
      get() {
        return this.dialogVisible
      },
      set(val) {
        this.$emit('update:dialogVisible', val)
      }
    },
  },
  watch: {
    currentStock(val) {
      this.syncCurrentStock();
    },
    dialogVisible(val) {
      this.syncCurrentStock();
    },
  },
  created() {
    this.syncCurrentStock();
  },
  methods: {
    syncCurrentStock() {
      if (this.currentSuit) {
        this.currentStock = this.currentSuit.goodsList[0].stockNum;
        this.formStock = this.currentStock;
      }
    },
    submitPacketStock() {
      console.log('this.currentSuit', this.currentSuit)
      if (!this.currentSuit) {
        return;
      }
      this.loading = true;
      // 这里直接提交
      const data = {
        suitId: this.currentSuit.id,
        packetStockList: [
          {
            suitListId: this.currentSuit.goodsList[0].id,
            stockNum: this.formStock,
            sku: this.currentSuit.goodsList[0].sku,
          }
        ],
      };
      editStockNum(data)
          .then(res => {
            this.loading = false;
            if(res.error === 0){
              this.computedDialogVisible = false;
              this.$emit('submitSuccess', this.formStock);
            } else {
              this.$message.error(res.message);
            }
          })
    },
  }
}
</script>

<style scoped lang="less">
.tips{
  color: red;
}
</style>
